package com.block.datapush.form.item;

import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.BaseTypeInfoEnum;
import com.block.common.service.LogFactory;
import com.block.datapush.form.service.IFormPushHandle;
import com.block.datapush.form.item.util.DaJinDaiUtil;
import com.block.datapush.model.dto.FormPushResultDTO;
import com.block.db.entity.FormInfo;
import com.block.db.entity.FormInfoHis;
import com.block.db.entity.MemberExtInfo;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class DaJinDaiPushHandleService implements IFormPushHandle {

    private static final Logger log = LogFactory.getCommLog();

    @Override
    public boolean queryMatchResult(FormInfo formInfo, MemberExtInfo memberExtInfo) {

        try {

            String queryUrl = formInfo.getQueryUrl();
            String mobileMd5 = SecureUtil.md5(memberExtInfo.getMobile()).toLowerCase();

            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("mobiles", mobileMd5);
            paramMap.put("channel", formInfo.getApiKey());

            log.info("【大金贷】撞库开始【queryUrl】{}【paramMap】{}", queryUrl, JSON.toJSONString(paramMap));
            String result = HttpUtil.createPost(queryUrl)
                    .header("Content-Type", "application/x-www-form-urlencoded")
                    .form(paramMap)
                    .execute().body();
            log.info("【大金贷】撞库结束【result】{}", result);

            JSONObject resultObject = JSON.parseObject(result);
            boolean success = resultObject.getBoolean("success");
            String errorCode = resultObject.getString("errorCode");
            String msg = resultObject.getString("msg");

            if (success){
                return true;
            }
            return false;
        }catch (Exception exception){
            exception.printStackTrace();
        }
        return false;
    }

    @Override
    public FormPushResultDTO pushMemberInfo(FormInfo formInfo, MemberExtInfo memberExtInfo, String orderNo, JSONObject extObject) {

        FormPushResultDTO pushResultDTO = new FormPushResultDTO();
        pushResultDTO.setOrderNo(orderNo);
        try {

            String requestUrl = formInfo.getRequestUrl();

            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("channel", formInfo.getApiKey());
            paramMap.put("reserved", orderNo);
            paramMap.put("ip", memberExtInfo.getReqIp());
            paramMap.put("mobile", memberExtInfo.getMobile());
            paramMap.put("name", memberExtInfo.getUsername());
            paramMap.put("id_card", memberExtInfo.getIdCard());
            paramMap.put("age", IdcardUtil.getAgeByIdCard(memberExtInfo.getIdCard()));
            paramMap.put("sex", IdcardUtil.getGenderByIdCard(memberExtInfo.getIdCard())==1?"male":"female");

            paramMap.put("work_city_name", DaJinDaiUtil.getCityName(memberExtInfo.getCity(), memberExtInfo.getProvince()));
            // TODO: 2022/11/22 获取城市编号
            paramMap.put("work_city", this.getCityCode(memberExtInfo.getCity()));
            paramMap.put("money", BaseTypeInfoEnum.LoanAmount.getEntryByValue(memberExtInfo.getLoanAmount()).getAmount());
            paramMap.put("limit", 12);

            paramMap.put("sb_security", DaJinDaiUtil.getShebao(memberExtInfo.getSocialInsurance()));
            paramMap.put("sb_fund", DaJinDaiUtil.getGjj(memberExtInfo.getGjj()));
            paramMap.put("sesame_credit", DaJinDaiUtil.getZhima(memberExtInfo.getZhimaScore()));
            paramMap.put("car", DaJinDaiUtil.getCar(memberExtInfo.getCar()));
            paramMap.put("house", DaJinDaiUtil.getHouse(memberExtInfo.getHouse()));
            paramMap.put("zy_insurance", DaJinDaiUtil.getBaodan(memberExtInfo.getInsurance()));

            // 默认
            paramMap.put("profession", 4);
            paramMap.put("zy_income", 8000);
            paramMap.put("wld_money", 0);
            paramMap.put("credit_card_money", 0);
            paramMap.put("purpose", 8);

            log.info("【大金贷】导单开始【requestUrl】{}【paramMap】{}", requestUrl, JSON.toJSONString(paramMap));
            String result = HttpUtil.createPost(requestUrl)
                    .header("Content-Type", "application/json")
                    .body(JSON.toJSONString(paramMap))
                    .execute().body();
            log.info("【大金贷】导单结束【result】{}", result);

            JSONObject resultObject = JSON.parseObject(result);

            boolean success = resultObject.getBoolean("success");
            String errorCode = resultObject.getString("errorCode");
            String msg = resultObject.getString("msg");

            pushResultDTO.setResult(result);
            pushResultDTO.setCode(errorCode);
            pushResultDTO.setMessage(msg);
            pushResultDTO.setParamContent(JSON.toJSONString(paramMap));
            if (success){
                JSONObject dataObject = resultObject.getJSONObject("data");
                pushResultDTO.setSuccess(true);
                pushResultDTO.setOutOrderNo(JSON.toJSONString(dataObject));
            }else{
                pushResultDTO.setSuccess(false);
            }
            return pushResultDTO;
        }catch (Exception exception){
            exception.printStackTrace();
        }
        return pushResultDTO;
    }


    /**
     * 查询城市编号
     * @param city
     * @return
     */
    public Integer getCityCode( String city){

        try {
            String extUrl = StrUtil.format("http://zhudai.bainiaofenqi.com/api/getcity?cityName={}", city);

            log.info("【佰鸟】查询城市编号开始【extUrl】{}", extUrl);
            String result = HttpUtil.get(extUrl);
            log.info("【佰鸟】查询城市编号结束【result】{}", result);

            JSONObject jsonObject = JSON.parseObject(result);
            Integer code = jsonObject.getInteger("code");
            String msg = jsonObject.getString("message");
            Integer cityCode = 0;
            if (ObjectUtil.equal(code, Integer.valueOf(1))){
                cityCode = jsonObject.getInteger("data");
            }
            return cityCode;
        }catch (Exception exception){
            log.error("【佰鸟】查询城市编号 异常", exception);
        }
        return 0;
    }

    @Override
    public void afterPushHandle(FormInfoHis formInfoHis) {

    }
}
